<template>
	<view class="w-100">
		<view class="bg-f1 h-100vh">
			<view class="pt-f left-0 w-100 p-0-32 bg-white z1000" :style="'height: 132rpx;top:0'">
				<view>
					<view class="fz-34 fw-b pt-20">
						{{ filmName }}
					</view>
					<view class="mt-10 fz-28 color-666">
						{{ time }} {{ lv }}
					</view>
				</view>
			</view>
			<movable-area :style="{
				height: calculateMovableAreaHeight + 'px',
				width: '100vw',
				top: rpxNum * 132 + 'px',
				position: 'fixed',
				left: 0,
				paddingLeft: actualSeatSize * 1.5 + 'px',
				paddingBottom: actualSeatSize * 1.5 + 'px'
			}" class="pt-f">
				<movable-view id="myMovableView" :style="{
					width: calculateSeatAreaWidth + 'px',
					height: calculateSeatAreaHeight + 'px',
					left: initialMoveX + 'px',
					top: initialMoveY + 'px',
					backgroundColor: '#f8f8f8',
					paddingLeft: actualSeatSize * 1.5 + 'px',
					paddingBottom: actualSeatSize * 1.5 + 'px',
					transformOrigin: scaleOrigin
				}" :inertia="true" :scale="true" :scale-min="calculateMinScale" :scale-max="3" :scale-value="initialScale"
					direction="all" @change="onMove" @scale="onScale">
					<view class="Stage dp-f jc-c ai-c" :style="{
						width: calculateScreenWidth + 'px',
						height: calculateScreenHeight + 'px',
						fontSize: calculateScreenFontSize + 'px',
						margin: '0 auto ' + calculateScreenMargin + 'px auto'
					}">
						{{ CheckHallName }}
					</view>
					<view v-for="(item, index) in seatArray" :key="'row-' + index" class="dp-f jc-c"
						:style="'width:' + calculateSeatAreaWidth + 'px;height:' + actualSeatSize + 'px;margin-top:' + seatPadding + 'px;'">
						<template v-for="(seat, col) in item">
							<!-- 处理情侣座 -->
							<view v-if="seat.isCoupleSeatStart" :key="'couple-' + index + '-' + col"
								class="couple-seat-wrapper"
								:style="'width:' + (actualSeatSize * 2) + 'px;height:' + actualSeatSize + 'px;'"
								@tap="handleChooseCoupleSeat(index, col)">
								<view class="dp-ib couple-seat" :class="[seat.priceClass]"
									:style="'width:' + actualSeatSize + 'px;height:' + actualSeatSize + 'px;'">
									<view v-if="seat.status == '0'" class="w-100 h-100"></view>
									<image v-if="seat.status == '1'" class="w-100 h-100"
										src="../static/assets/unselected.png" mode="aspectFit"></image>
									<image v-else-if="seat.status == '4'" class="w-100 h-100"
										src="../static/assets/selected.png" mode="aspectFit"></image>
									<image v-else-if="seat.status == '2' || seat.status == '3'" class="w-100 h-100"
										src="../static/assets/bought.png" mode="aspectFit"></image>
								</view>
								<view class="dp-ib couple-seat" :class="[item[col + 1].priceClass]"
									:style="'width:' + actualSeatSize + 'px;height:' + actualSeatSize + 'px;'">
									<view v-if="item[col + 1].status == '0'" class="w-100 h-100"></view>
									<image v-if="item[col + 1].status == '1'" class="w-100 h-100"
										src="../static/assets/unselected.png" mode="aspectFit"></image>
									<image v-else-if="item[col + 1].status == '4'" class="w-100 h-100"
										src="../static/assets/selected.png" mode="aspectFit"></image>
									<image v-else-if="item[col + 1].status == '2' || item[col + 1].status == '3'"
										class="w-100 h-100" src="../static/assets/bought.png" mode="aspectFit"></image>
								</view>
							</view>
							<!-- 普通座位 -->
							<view v-else-if="!seat.isCoupleSeatEnd" :key="'seat-' + index + '-' + col" class="dp-ib"
								:class="seat.priceClass"
								:style="'width:' + actualSeatSize + 'px;height:' + actualSeatSize + 'px;margin-left:' + seatPadding + 'px;'"
								@tap="handleChooseSeat(index, col)">
								<view v-if="seat.status == '0'" class="w-100 h-100"></view>
								<image v-if="seat.status == '1'" class="w-100 h-100"
									src="../static/assets/unselected.png" mode="aspectFit"></image>
								<image v-else-if="seat.status == '4'" class="w-100 h-100"
									src="../static/assets/selected.png" mode="aspectFit"></image>
								<image v-else-if="seat.status == '2' || seat.status == '3'" class="w-100 h-100"
									src="../static/assets/bought.png" mode="aspectFit"></image>
							</view>
						</template>
					</view>
					<!-- 座位序号图例 -->
					<view class="seat-indicators" :style="{
						left: calculateIndicatorPosition() + 'px',
						top: calculateIndicatorVerticalPosition() + 'px',
						width: actualSeatSize + 'px',
						background: 'rgba(0, 0, 0, 0.6)',
						borderRadius: '15rpx',
						overflow: 'hidden',
						position: 'absolute'
					}">
						<view v-for="(row, index) in seatArray" :key="index"
							class="w-100 dp-f ai-c jc-c fz-22 color-fff"
							:style="'height:' + actualSeatSize + 'px;margin-top:2rpx;font-size:' + actualSeatSize + 'px'">
							{{ hasValidSeats(row) ? getRowNumber(index) : '' }}
						</view>
					</view>
				</movable-view>
			</movable-area>

			<view class="pt-f bottom-bar left-0 dp-f fd-cr z1000">
				<!-- v-if="showTis" -->
				<view class="legend-area">
					<view class="legend-list">
						<!-- 价格图例 -->
						<view class="legend-item" v-for="price in priceList" :key="price">
							<view class="seat-demo" :class="'price-' + priceList.indexOf(price)">
								<image class="w-100 h-100" src="../static/assets/unselected.png" mode="aspectFit">
								</image>
							</view>
							<text class="price-text">￥{{ price }}</text>
						</view>
						<!-- 状态图例 -->
						<view class="legend-item">
							<image class="legend-icon" src="../static/assets/bought.png" mode="aspectFit"></image>
							<text class="status-text">不可选</text>
						</view>
						<view class="legend-item">
							<image class="legend-icon" src="../static/assets/selected.png" mode="aspectFit"></image>
							<text class="status-text">选中</text>
						</view>
						<!-- 情侣座图例 -->
						<view class="legend-item">
							<view class="couple-seat-demo">
								<image class="w-100 h-100" src="../static/assets/unselected.png" mode="aspectFit">
								</image>
								<image class="w-100 h-100" src="../static/assets/unselected.png" mode="aspectFit">
								</image>
							</view>
							<text class="status-text">情侣座</text>
						</view>
					</view>
				</view>
				<!-- 底部内容区域 -->
				<view class="bottom-content">
					<!-- 已选座位区域 -->
					<view class="selected-seats-area">
						<scroll-view scroll-x enable-flex class="selected-seats-scroll" :show-scrollbar="false">
							<view class="selected-seats-container" v-if="selectedSeats.length > 0">
								<view class="seats-list">
									<view class="seat-item" v-for="(seat, index) in selectedSeats" :key="index"
										@tap="cancelSeat(seat)">
										<view class="seat-info">
											<text class="seat-name">{{ seat.name }}</text>
											<text class="seat-price">¥{{ seat.price }}</text>
										</view>
										<text class="cancel-icon">×</text>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<!-- 购票方式区域 -->
					<!-- <view class="ticket-method">
						<view class="method-row">
							<text class="method-label">购票方式</text>
							<view class="method-right">
								<text class="method-name">极速购票</text>
								<text class="method-time">16分钟内出票</text>
								<text class="method-price">¥{{ getTotalPrice() }}</text>
								<text class="method-check">✓</text>
							</view>
						</view>
						<view class="refund-tip">不出票必退</view>
					</view> -->

					<!-- 确认按钮 -->
					<view class="confirm-btn" :class="selectedSeats.length > 0 ? 'active' : 'disabled'" @tap="buySeat">
						¥{{ getTotalPrice() }}确认选座
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
var app = getApp();
// import mockData from '../static/mock_data/data.json'
export default {
	data() {
		return {
			filmName: '',
			time: '',
			lv: '',
			hallName: '',
			scaleMin: 1,
			boxWidth: 400,
			space: ' ',
			seatArray: [],
			seatRow: 0,
			seatCol: 0,
			baseSeatSize: 40, // 基础座位大小
			seatSize: 40,
			moveX: 0,
			scale: 1,
			minRow: 0,
			minCol: 0,
			showTis: true,
			seatList: [],
			mArr: [],
			optArr: [],
			isWXAPP: false,
			selectedSeats: [],
			maxSelect: 99999,
			selectedRow: 0,
			priceList: [],
			initialScale: 1.3,
			defaultSeatSize: 25,
			initialMoveX: 0,
			initialMoveY: 0,
			params: null,
			screenWidth: 375,
			screenHeight: 667,
			minSeatSize: 25, // 最小座位大小
			maxSeatSize: 40, // 最大座位大小
			seatPadding: 2, // 座位间距
			seatBaseSize: 0, // 基础座位大小(vw)
			screenRatio: 0.6, // 荧幕宽度占座位区域的比例
			isSeatsRendered: false, // 标记座位是否渲染完成
			scaleOrigin: '0 0'
		};
	},
	computed: {
		aPrice() {
			return this.SelectNum * 36
		},
		rpxNum() {
			return this.boxWidth / 750
		},
		pxNum() {
			return 750 / this.boxWidth
		},
		// 计算实际座位大小(px)
		actualSeatSize() {
			console.log("实际座位大小(px)", Math.floor(this.screenWidth * 0.1))
			// 固定座位大小为屏幕宽度的10%
			return Math.floor(this.screenWidth * 0.1);
		},
		// 计算座位区域宽度
		calculateSeatAreaWidth() {
			return this.seatCol * (this.actualSeatSize + this.seatPadding * 2);
		},
		// 计算座位区域高度
		calculateSeatAreaHeight() {
			return this.seatRow * (this.actualSeatSize + this.seatPadding * 2);
		},
		// 计算可移动区域高度
		calculateMovableAreaHeight() {
			return Math.max(this.screenHeight * 0.6, this.calculateSeatAreaHeight + 100);
		},
		// 计算最小缩放比例
		calculateMinScale() {
			if (!this.seatRow || !this.seatCol) return 1;

			// 计算屏幕可用区域
			const availableWidth = this.screenWidth * 0.9;
			const availableHeight = this.screenHeight * 0.6;

			// 计算座位区域实际大小
			const seatAreaWidth = this.calculateSeatAreaWidth;
			const seatAreaHeight = this.calculateSeatAreaHeight;

			// 计算缩放比例
			const widthRatio = availableWidth / seatAreaWidth;
			const heightRatio = availableHeight / seatAreaHeight;

			// 根据座位数量调整最小缩放比例
			let minScale = Math.min(widthRatio, heightRatio);

			// 座位数量少时保持较大的显示比例
			const totalSeats = this.seatRow * this.seatCol;
			if (totalSeats < 100) {
				minScale = Math.max(minScale, 0.8);
			} else if (totalSeats < 200) {
				minScale = Math.max(minScale, 0.6);
			} else {
				minScale = Math.max(minScale, 0.4);
			}

			return minScale;
		},
		// 计算初始缩放比例
		calculateInitialScale() {
			return Math.max(this.calculateMinScale * 1.2, 1.3);
		},
		// 计算荧幕宽度
		calculateScreenWidth() {
			return this.calculateSeatAreaWidth * this.screenRatio;
		},

		// 计算荧幕高度
		calculateScreenHeight() {
			return Math.max(34, this.calculateScreenWidth * 0.1);
		},

		// 计算荧幕字体大小
		calculateScreenFontSize() {
			return Math.max(22, this.calculateScreenWidth * 0.05);
		},

		// 计算荧幕底部边距
		calculateScreenMargin() {
			return this.calculateScreenHeight * 0.5;
		},

		CheckHallName() {
			return this.hallName.replace(/（[^（）]*）/g, '');
		}
	},
	onLoad: function (option) {
		//获取宽度
		var that = this
		uni.getSystemInfo({
			success: function (e) {
				that.boxWidth = e.screenWidth
				//#ifdef H5
				this.scaleMin = 0.95
				//#endif
			}
		})

		try {
			if (option && option.params) {
				//路由拼接传参改为对象编码传参
				const decodedParams = JSON.parse(decodeURIComponent(option.params));
				this.params = decodedParams;

				// 设置影片信息
				that.filmName = this.params.filmName || '';
				that.time = this.params.time || '';
				that.lv = this.params.lv || '';
				that.hallName = this.params.hallName || '';
			} else {
				// 如果没有参数，可以设置默认值或者处理错误
				console.log('No params provided');
				this.params = {
					filmName: '测试电影',
					time: '2024-01-01 14:30',
					lv: '国语 2D',
					hallName: '1号厅',
					showId: '1',
					cinemaId: '1'
				};
				that.filmName = this.params.filmName;
				that.time = this.params.time;
				that.lv = this.params.lv;
				that.hallName = this.params.hallName;
			}
		} catch (error) {
			console.error('Error parsing params:', error);
			// 处理错误情况
			this.params = {
				filmName: '测试电影',
				time: '2024-01-01 14:30',
				lv: '国语 2D',
				hallName: '1号厅',
				showId: '1',
				cinemaId: '1'
			};
			that.filmName = this.params.filmName;
			that.time = this.params.time;
			that.lv = this.params.lv;
			that.hallName = this.params.hallName;
		}

		// 加载座位数据
		this.loadData();
	},
	mounted() {

	},
	methods: {

		initData: function () {
			uni.showLoading({
				title: "正在加载座位"
			})

			var that = this;

			app.post('film/get_cinema_seats', {
				showId: that.params.showId,
				cinemaId: that.params.cinemaId,
			}, function (res) {
				//urlRequestWithUserId("后台地址", param, "POST", function (res) {
				//that.filmName = res.data.film_name;
				//that.time = res.data.film_date + "  " + res.data.film_start_time + " - " + res.data.film_end_time
				that.seatArray = res.data.filmSeat
				that.seatRow = that.seatArray.length; //行数量
				that.seatCol = that.seatArray[0].length; //列数量
				//设置座位大小
				that.seatSize = that.boxWidth > 0 ?
					parseInt(parseInt(that.boxWidth, 10) / (that.seatCol + 1), 10) :
					parseInt(parseInt(414, 10) / (that.seatCol + 1), 10)
				// console.log(that.seatArray)

				//左侧导航条
				let arr = that.seatArray.slice()
				let mArr = []
				var num = 1;
				for (let i in arr) {
					var flag = false;
					for (let m in arr[i]) {
						if (arr[i][m].num != '') {
							//一行里只要有num不是空的则需要显示序号
							flag = true;
						}
					}
					if (flag) {
						mArr.push(num++)
					} else {
						mArr.push('')
					}
				}
				that.mArr = mArr
			})

			uni.hideLoading();
		},


		loadData: function () {
			app.showLoading('加载座位中...');
			var that = this;

			// 初始化屏幕尺寸
			this.initScreenSize();

			// 直接使用导入的 mockData
			// let res1 = mockData;

			app.post('film/get_cinema_seats', {
				showId: that.params.showId,
				cinemaId: that.params.cinemaId,
			}, function (res) {
				if (1 || res && res.status == 200) {
					//if (res1) {
					//const seatData = res1.data;
					const seatData = res.data;

					that.seatRow = seatData.rows;
					that.seatCol = seatData.columns;

					// 更新初始缩放和位置
					that.updateInitialScaleAndPosition();

					// 初始化座位数组
					let seatArray = [];
					for (let i = 0; i < seatData.rows; i++) {
						let row = [];
						for (let j = 0; j < seatData.columns; j++) {
							row.push({
								status: "0",
								num: "",
								row: i + 1,
								column: j + 1
							});
						}
						seatArray.push(row);
					}

					// 提取不同的价格并排序
					const prices = new Set();
					Object.values(seatData.seats).forEach(seat => {
						if (seat.showPrice) {
							prices.add(seat.showPrice);
						}
					});
					that.priceList = Array.from(prices).sort((a, b) => a - b);

					// 填充有效座位
					Object.entries(seatData.seats).forEach(([key, seat]) => {
						const rowIndex = seat.row - 1;
						const colIndex = seat.column - 1;
						if (rowIndex >= 0 && rowIndex < seatData.rows &&
							colIndex >= 0 && colIndex < seatData.columns) {
							seatArray[rowIndex][colIndex] = {
								status: seat.status.toString(),
								num: seat.column.toString(),
								row: seat.row,
								column: seat.column,
								seatId: seat.seatId,
								name: seat.name,
								price: seat.showPrice,
								priceClass: 'price-' + that.priceList.indexOf(seat.showPrice),
								flag: seat.flag,
								isCoupleSeatStart: seat.flag === 1 && seatData.seats[
									`${seat.row}-${seat.column + 1}`]?.flag === 2,
								isCoupleSeatEnd: seat.flag === 2 && seatData.seats[
									`${seat.row}-${seat.column - 1}`]?.flag === 1
							};
						}
					});

					that.seatArray = seatArray;

					// 生成左侧行号
					let mArr = [];
					for (let i = 0; i < seatArray.length; i++) {
						let hasSeats = seatArray[i].some(seat => seat.num !== "");
						mArr.push(hasSeats ? (i + 1) : "");
					}
					that.mArr = mArr;

					// 标记座位渲染完成，并在下一帧更新位置
					that.$nextTick(() => {
						that.isSeatsRendered = true;
						that.updateInitialScaleAndPosition();
						// 渲染完成后取消缩放焦点设置
						setTimeout(() => {
							that.scaleOrigin = 'center center'; // 重置缩放焦点为中心
							app.showLoading(false);
						}, 1000); // 1 秒后重置
					});


				} else {
					app.showLoading(false);
					app.error("数据加载错误：" + res.msg);
					setTimeout(() => {
						uni.navigateBack();
					}, 1700);
				}
			});
		},

		//放大缩小事件
		onScale: function (e) {
			this.showTis = false;
			this.scale = e.detail.scale;
			// console.log("this.scale", this.scale)
			// 计算缩放后的位置，保持居中
			const screenWidth = uni.getSystemInfoSync().windowWidth;
			const totalWidth = this.actualSeatSize * this.seatCol;
			const scaledWidth = totalWidth * this.scale;
			//const newMoveX = (screenWidth - scaledWidth) / 2;

			// 平滑过渡到新位置
			//this.moveX = newMoveX;
		},
		//移动事件
		onMove: function (e) {
			this.showTis = false;
			this.moveX = e.detail.x;
			//console.log("this.initialMoveX", this.initialMoveX)
			// 添加边界限制
			const screenWidth = uni.getWindowInfo().windowWidth;
			const totalWidth = this.actualSeatSize * this.seatCol * this.scale;
			const minX = screenWidth - totalWidth;
			const maxX = 0;
			//console.log("moveX:",screenWidth,totalWidth,this.moveX,minX)
			if (this.moveX < minX) this.moveX = minX;
			if (this.moveX > maxX) this.moveX = maxX;
		},
		//选定且购买座位
		buySeat: function () {

			if (this.selectedSeats.length === 0) {
				uni.showToast({
					title: '请先选择座位',
					icon: 'none'
				});
				return;
			}

			// uni.showLoading({
			// 	title: '正在确认座位'
			// });

			// 这里可以添加实际的座位预订逻辑
			// setTimeout(() => {
			// 	uni.hideLoading();
			// 	uni.showToast({
			// 		title: '选座成功',
			// 		icon: 'success'
			// 	});
			// }, 1000);	
			const params = {
				cinemaId: this.params.cinemaId,
				showId: this.params.showId,
				pic: this.params.pic,
				hallName: this.params.hallName,
				cinemaName: this.params.cinemaName,
				seats: this.selectedSeats.map(c => { return c.name }),
				seatsPrice: this.selectedSeats.map(c => { return c.price }),
				filmName: this.params.filmName,
				time: this.params.time,
				lv: this.params.lv,
				title: this.params.filmName + ' ' + this.params.time + ' ' + this.params.lv,
				price: this.getTotalPrice(),
				changeSeat: 2,
				deliverMinute: 0,
				singleCode: 1,
				disallowUpdate: 1,
				maxPrice: this.priceList,
				// filmName: this.movieList[this.currentIndex].filmName,
				// time: this.getftime(item.startTime, item.endTime),
				// lv: item.language + ' ' + item.version,
				// hallName:item.hallName
			};
			//console.log("this.params",params)
			const encodedParams = encodeURIComponent(JSON.stringify(params));

			// 可以跳转到订单确认页面
			uni.navigateTo({
				url: `/pagesZone/movie/confirm?params=${encodedParams}`
			});
		},
		//处理座位选择逻辑
		handleChooseSeat: function (row, col) {
			let seat = this.seatArray[row][col];
			if (!seat || seat.status === '0' || seat.status === '2' || seat.status === '3') {
				return;
			}

			let newArray = [...this.seatArray];

			if (seat.status === '4') {
				// 取消选中
				newArray[row][col].status = '1';
				this.selectedSeats = this.selectedSeats.filter(s =>
					!(s.row === seat.row && s.column === seat.column)
				);
			} else if (seat.status === '1') {
				// 选中新座位
				if (this.selectedSeats.length >= this.maxSelect) {
					uni.showToast({
						title: `最多只能选择${this.maxSelect}个座位`,
						icon: 'none'
					});
					return;
				}

				newArray[row][col].status = '4';
				this.selectedSeats.push(newArray[row][col]);
			}

			this.seatArray = newArray;
		},
		//处理已选座位数组
		getOptArr: function (item, type) {
			// let optArr = this.optArr
			let optArr = [];
			if (type === 1) {
				optArr.push(item)
				this.
					//上一个选中的置为未选中
					this.selectedSeats = [item];
			} else if (type === 0) {
				let arr = []
				optArr.forEach(v => {
					if (v.SeatCode !== item.SeatCode) {
						arr.push(v)
					}
				})
				optArr = arr
			}
			this.optArr = optArr.slice()
		},
		//推荐选座,参数是推荐座位数目，
		smartChoose: function (num) {
			console.log('num===', num)
			// 先重置
			this.resetSeat()
			//找到影院座位水平垂直中间位置的后一排
			let rowStart = parseInt((this.seatRow - 1) / 2, 10) + 1;
			//先从中间排往后排搜索
			let backResult = this.searchSeatByDirection(rowStart, this.seatRow - 1, num);
			if (backResult.length > 0) {
				this.chooseSeat(backResult);
				this.SelectNum += num
				return
			}
			//再从中间排往前排搜索
			let forwardResult = this.searchSeatByDirection(rowStart - 1, 0, num);
			if (forwardResult.length > 0) {
				this.chooseSeat(forwardResult);
				this.SelectNum += num
				return
			}
			//提示用户无合法位置可选
			alert('无合法位置可选!')

		},

		//搜索函数,参数:fromRow起始行，toRow终止行,num推荐座位数
		searchSeatByDirection: function (fromRow, toRow, num) {
			/*
			 * 推荐座位规则
			 * (1)初始状态从座位行数的一半处的后一排的中间开始向左右分别搜索，取离中间最近的，如果满足条件，
			 *    记录下该结果离座位中轴线的距离，后排搜索完成后取距离最小的那个结果座位最终结果，优先向后排进行搜索，
			 *    后排都没有才往前排搜，前排逻辑同上
			 *
			 * (2)只考虑并排且连续的座位，不能不在一排或者一排中间有分隔
			 *
			 * */

			/*
			 * 保存当前方向搜索结果的数组,元素是对象,result是结果数组，offset代表与中轴线的偏移距离
			 * {
			 *   result:Array([x,y])
			 *   offset:Number
			 * }
			 *
			 */
			let currentDirectionSearchResult = [];

			let largeRow = fromRow > toRow ? fromRow : toRow,
				smallRow = fromRow > toRow ? toRow : fromRow;

			for (let i = smallRow; i <= largeRow; i++) {
				//每一排的搜索,找出该排里中轴线最近的一组座位
				let tempRowResult = [],
					minDistanceToMidLine = Infinity;
				for (let j = 0; j <= this.seatCol - num; j++) {
					//如果有合法位置
					if (this.checkRowSeatContinusAndEmpty(i, j, j + num - 1)) {
						//计算该组位置距离中轴线的距离:该组位置的中间位置到中轴线的距离
						let resultMidPos = parseInt((j + num / 2), 10);
						let distance = Math.abs(parseInt(this.seatCol / 2) - resultMidPos);
						//如果距离较短则更新
						if (distance < minDistanceToMidLine) {
							minDistanceToMidLine = distance;
							//该行的最终结果
							tempRowResult = this.generateRowResult(i, j, j + num - 1)
						}
					}
				}
				//保存该行的最终结果
				currentDirectionSearchResult.push({
					result: tempRowResult,
					offset: minDistanceToMidLine
				})
			}

			//处理后排的搜索结果:找到距离中轴线最短的一个
			//注意这里的逻辑需要区分前后排，对于后排是从前往后，前排则是从后往前找
			let isBackDir = fromRow < toRow;
			let finalReuslt = [],
				minDistanceToMid = Infinity;
			if (isBackDir) {
				//后排情况,从前往后
				currentDirectionSearchResult.forEach((item) => {
					if (item.offset < minDistanceToMid) {
						finalReuslt = item.result;
						minDistanceToMid = item.offset;
					}
				});
			} else {
				//前排情况，从后往前找
				currentDirectionSearchResult.reverse().forEach((item) => {
					if (item.offset < minDistanceToMid) {
						finalReuslt = item.result;
						minDistanceToMid = item.offset;
					}
				})
			}

			//直接返回结果
			return finalReuslt
		},

		/*辅助函数，判断每一行座位从i列到j列是否全部空余且连续
		 *
		 */
		checkRowSeatContinusAndEmpty: function (rowNum, startPos, endPos) {
			let isValid = true;
			for (let i = startPos; i <= endPos; i++) {
				if (this.seatArray[rowNum][i].type !== 0) {
					isValid = false;
					break;
				}
			}
			return isValid
		},
		//辅助函数：返回每一行的某个合理位置的座位数组
		generateRowResult: function (row, startPos, endPos) {
			let result = [];
			for (let i = startPos; i <= endPos; i++) {
				result.push([row, i])
			}
			return result
		},
		//辅助函数:智能推荐的选座操作
		chooseSeat: function (result) {
			let opt = this.optArr
			let oldArray = this.seatArray.slice();
			for (let i = 0; i < result.length; i++) {
				//选定座位
				oldArray[result[i][0]][result[i][1]].type = 1
				this.optArr.push(oldArray[result[i][0]][result[i][1]])
			}
			this.seatArray = oldArray;
		},
		// 处理情侣座选择
		handleChooseCoupleSeat(row, col) {
			const seat1 = this.seatArray[row][col];
			const seat2 = this.seatArray[row][col + 1];

			// 如果任一座位不可选，则返回
			if (seat1.status === '2' || seat1.status === '3' ||
				seat2.status === '2' || seat2.status === '3') {
				return;
			}

			// 如果已经选中，则取消选择
			if (seat1.status === '4') {
				this.seatArray[row][col].status = '1';
				this.seatArray[row][col + 1].status = '1';
				this.selectedSeats = this.selectedSeats.filter(s =>
					s.seatId !== seat1.seatId && s.seatId !== seat2.seatId
				);
			} else {
				// 选中两个座位
				if (this.selectedSeats.length + 2 > this.maxSelect) {
					uni.showToast({
						title: `最多只能选择${this.maxSelect}个座位`,
						icon: 'none'
					});
					return;
				}
				this.seatArray[row][col].status = '4';
				this.seatArray[row][col + 1].status = '4';
				this.selectedSeats.push(seat1, seat2);
			}
		},
		// 修改取消座位方法
		cancelSeat(seat) {
			const row = seat.row - 1;
			const col = seat.column - 1;
			const currentSeat = this.seatArray[row][col];

			if (currentSeat.flag === 1 || currentSeat.flag === 2) {
				// 是情侣座,需要同时取消相邻座位
				let otherCol;
				if (currentSeat.flag === 1) {
					otherCol = col + 1;
				} else {
					otherCol = col - 1;
				}

				this.seatArray[row][col].status = '1';
				this.seatArray[row][otherCol].status = '1';
				this.selectedSeats = this.selectedSeats.filter(s =>
					s.seatId !== this.seatArray[row][col].seatId &&
					s.seatId !== this.seatArray[row][otherCol].seatId
				);
			} else {
				// 普通座位
				this.seatArray[row][col].status = '1';
				this.selectedSeats = this.selectedSeats.filter(s => s.seatId !== seat.seatId);
			}
		},
		// 计算总价
		getTotalPrice() {
			return this.selectedSeats.reduce((total, seat) => {
				return total + Number(seat.price);
			}, 0).toFixed(2);
		},
		// 检查该行是否有有效座位
		hasValidSeats(row) {
			return row.some(seat => seat.status !== '0');
		},
		// 获取实际行号（跳过空行）
		getRowNumber(currentIndex) {
			let actualRow = 1;
			for (let i = 0; i < currentIndex; i++) {
				if (this.hasValidSeats(this.seatArray[i])) {
					actualRow++;
				}
			}
			return actualRow;
		},
		calculateIndicatorPosition() {
			const baseOffset = 10; // 基准偏移值
			const adjustedMove = this.moveX / this.scale; // 考虑缩放的实际移动距离
			return baseOffset - adjustedMove;
		},
		// 计算指示器的垂直位置
		calculateIndicatorVerticalPosition() {
			const screenHeight = this.calculateScreenHeight;
			const screenMargin = this.calculateScreenMargin;
			return screenHeight + screenMargin + (this.moveY || 0) / this.scale;
		},
		// 初始化屏幕尺寸
		initScreenSize() {
			const systemInfo = uni.getSystemInfoSync();
			this.screenWidth = systemInfo.windowWidth;
			this.screenHeight = systemInfo.windowHeight;
		},
		// 更新初始缩放和位置
		updateInitialScaleAndPosition() {

			this.initialScale = this.calculateMinScale;
			//this.initialMoveX = (this.screenWidth - this.calculateSeatAreaWidth * this.initialScale) / 10;
			//this.initialMoveX = 0;
			//this.scale = this.initialScale;
			// console.log("this.initialMoveX", this.initialMoveX)
			// console.log("this.initialScale", this.initialScale)
			// console.log("this.scale", this.scale)
			return;
			// 计算初始缩放比例
			const availableWidth = this.screenWidth * 0.9;
			const availableHeight = this.screenHeight * 0.6;

			const widthScale = availableWidth / this.calculateSeatAreaWidth;
			const heightScale = availableHeight / this.calculateSeatAreaHeight;

			// 设置初始缩放比例
			this.initialScale = Math.max(Math.min(widthScale, heightScale), this.calculateMinScale);

			// 计算初始位置使座位区域居中
			// 
			// this.initialMoveY = 50;
			console.log("this.initialMoveX", this.initialMoveX);
			console.log("this.initialMoveY", this.initialMoveY);
			console.log("this.initialScale", this.initialScale);

			// 如果座位已渲染完成，强制更新位置
			if (this.isSeatsRendered) {
				// 使用 uni.createSelectorQuery 替代 document.querySelector
				const query = uni.createSelectorQuery().in(this);
				query.select('.movable-view').boundingClientRect(data => {
					if (data) {
						// 使用 movable-view 的属性来更新位置和缩放
						this.moveX = this.initialMoveX;
						this.scale = this.initialScale;
					}
				}).exec();
			}
		},
	}
}
</script>

<style lang="scss" scoped>
.p-all-10 {
	padding: 10rpx;
}

.ml-10 {
	margin-left: 10rpx;
}

.m-0-10 {
	margin: 0 10rpx;
}

.bg-unbtn {
	background-color: #f9abb3;
}

.bg-red-1 {
	background-color: #F45664;
}

.br-10 {
	border-radius: 10rpx;
}

.ml-20 {
	margin-left: 20rpx;
}

.mb-20 {
	margin-bottom: 20rpx;
}

.p-all-32 {
	padding: 32rpx;
}

.fd-cr {
	flex-direction: column;
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #fff;
	z-index: 1000;
	padding-bottom: env(safe-area-inset-bottom);
}

.color-fff {
	color: #fff
}

.br-15 {
	border-radius: 15rpx;
}

.over-h {
	overflow: hidden;
}

.dp-ib {
	display: inline-block;
}

.mt-20 {
	margin-top: 20rpx;
}

.pa-v-2 {
	/* 定位垂直对齐 */
	left: 50%;
	transform: translateX(-50%)
}

.b-d-1 {
	border: 1px dashed #e5e5e5;
}

.w-100 {
	width: 100%;
	display: block;
}

.h-100 {
	height: 100%;
}

.bg-f1 {
	background-color: #f1f1f1;
}

.h-100vh {
	height: 100vh;
}

.pt-f {
	position: fixed;
}

.left-0 {
	left: 0;
}

.p-0-32 {
	padding: 0 32rpx;
}

.pt-20 {
	padding-top: 20rpx;
}

.bg-white {
	background-color: #fff;
}

.z1000 {
	z-index: 1000;
}

.fz-34 {
	font-size: 34rpx;
}

.fw-b {
	font-weight: bold;
}

.mt-10 {
	margin-top: 10rpx;
}

.fz-28 {
	font-size: 28rpx;
}

.color-666 {
	color: #666666
}

.dp-f {
	display: flex;
}

.jc-c {
	justify-content: center;
}

.ai-c {
	align-items: center;
}

.fz-22 {
	font-size: 22rpx;
}

.color-333 {
	color: #333333
}

.m-0-a {
	margin: 0 auto;
}

.mt-48 {
	margin-top: 48rpx;
}

.fz-20 {
	font-size: 20rpx;
}

.color-999 {
	color: #999999
}

.b-1 {
	border: 1px solid #CCCCCC;
}

.br-5 {
	border-radius: 5rpx;
}

.Stage {
	background-color: #dddddd;
	transform: perspective(100px) rotateX(-10deg);
	transition: all 0.3s ease;
	display: flex;
	justify-content: center;
	align-items: center;
	color: #333333;
}

.bg-line {
	background-color: rgba(0, 0, 0, 0.3);
}

.sel-seat {
	background: url('../static/assets/selected.png') center center no-repeat;
	background-size: 100% 100%;
}

.unsel-seat {
	background: url('../static/assets/unselected.png') center center no-repeat;
	background-size: 100% 100%;
}

.bought-seat {
	background: url('../static/assets/bought.png') center center no-repeat;
	background-size: 100% 100%;
}

.selected-seats {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
}

.seat-tag {
	position: relative;
	padding: 10rpx 40rpx 10rpx 20rpx;
	background: #f5f5f5;
	border-radius: 4rpx;
	font-size: 24rpx;
	color: #666;
	cursor: pointer;
	transition: all 0.3s;

	&:active {
		background: #e5e5e5;
	}

	.cancel-icon {
		position: absolute;
		right: 10rpx;
		color: #999;
		font-size: 28rpx;
	}
}

.seat-demo {
	width: 40rpx;
	height: 40rpx;
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;

	image {
		width: 100%;
		height: 100%;
	}
}

/* 为不同价格的座位添加不同颜色的边框 */
.price-0 {
	/* 最低价格座位无边框 */
}

.price-1 {
	border: 4rpx solid #FF9800;
	border-radius: 10rpx;
	/* 橙色边框 */
}

.price-2 {
	border: 4rpx solid #4CAF50;
	border-radius: 10rpx;
	/* 绿色边框 */
}

.price-3 {
	border: 4rpx solid #2196F3;
	border-radius: 10rpx;
	/* 蓝色边框 */
}

.price-4 {
	border: 4rpx solid #694d9f;
	border-radius: 10rpx;
	/* 菖蒲色边框 */
}

.price-5 {
	border: 4rpx solid #130c0e;
	border-radius: 10rpx;
	/* 黑色边框 */
}


.price-6 {
	border: 4rpx solid #87843b;
	border-radius: 10rpx;
	/* 莺色边框 */
}

.price-7 {
	border: 4rpx solid #65c294;
	border-radius: 10rpx;
	/* 若竹色边框 */
}

/* 图例容器样式 */
.legend-container {
	padding: 20rpx;
	background: #fff;
	border-top: 1rpx solid #eee;
}

/* 图例列表容器 */
.legend-list {
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	gap: 20rpx;
	width: 100%;
	padding: 0 20rpx;
}

/* 图例项样式 */
.legend-item {
	display: flex;
	align-items: center;
	padding: 4rpx 10rpx;
}

.legend-icon {
	width: 40rpx;
	height: 40rpx;
}

/* 座位示例样式 */
.seat-demo {
	width: 40rpx;
	height: 40rpx;
	flex-shrink: 0;
}

/* 已选座位滚动区域样式 */
.selected-seats-scroll {
	width: 100%;
	margin-bottom: 20rpx;
}

.selected-seats-container {
	display: flex;
	align-items: center;
	width: fit-content;
	min-width: 100%;

	.label {
		flex-shrink: 0;
		font-size: 28rpx;
		color: #333;
		margin-right: 20rpx;
	}

	.seats-list {
		display: flex;
		flex-wrap: nowrap;
		flex: 1;
	}

	.seat-item {
		display: inline-flex;
		align-items: center;
		position: relative;
		padding: 10rpx 40rpx 10rpx 20rpx;
		background: #f5f5f5;
		border: 1px solid #CCCCCC;
		border-radius: 4rpx;
		font-size: 24rpx;
		color: #666;
		margin-right: 16rpx;
		white-space: nowrap;

		.cancel-icon {
			position: absolute;
			right: 10rpx;
			color: #999;
			font-size: 28rpx;
		}

		&:active {
			background: #e5e5e5;
		}
	}
}

/* 移除之前的重复样式 */
.selected-seats-wrapper,
.selected-seat-tag,
.selected-label,
.selected-seats-list {
	display: none;
}

/* 底部区域样式 */
.bottom-content {
	width: 100%;
	padding: 20rpx;
}

.selected-seats-area {
	padding: 10rpx 0;
	margin-bottom: 10rpx;
}

.seats-list {
	display: flex;
	flex-wrap: nowrap;
}

.seat-item {
	position: relative;
	display: flex;
	align-items: center;
	background: #f7f7f7;
	border-radius: 8rpx;
	padding: 10rpx 40rpx 10rpx 20rpx;
	margin-right: 20rpx;
}

.seat-info {
	display: flex;
	flex-direction: column;
}

.seat-name {
	font-size: 28rpx;
	color: #333;
}

.seat-price {
	font-size: 24rpx;
	color: #ff4d4f;
	margin-top: 4rpx;
}

.cancel-icon {
	position: absolute;
	right: 10rpx;
	top: 50%;
	transform: translateY(-50%);
	font-size: 28rpx;
	color: #999;
	padding: 4rpx;
}

.ticket-method {
	background: #fff5f5;
	border-radius: 8rpx;
	padding: 20rpx;
	margin: 10rpx 0;
}

.method-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.method-label {
	font-size: 28rpx;
	color: #333;
}

.method-right {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.method-name {
	font-size: 28rpx;
	color: #333;
}

.method-time {
	font-size: 24rpx;
	color: #666;
}

.method-price {
	font-size: 32rpx;
	color: #ff4d4f;
}

.method-check {
	width: 36rpx;
	height: 36rpx;
	line-height: 36rpx;
	text-align: center;
	background: #ff4d4f;
	border-radius: 50%;
	color: #fff;
	font-size: 24rpx;
}

.refund-tip {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 10rpx;
}

.confirm-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	font-size: 32rpx;
	color: #fff;
	border-radius: 8rpx;
	margin-top: 20rpx;
}

.confirm-btn.active {
	background: #ff4d4f;
}

.confirm-btn.disabled {
	background: #ccc;
}

/* 图例区域样式 */
.legend-area {
	position: relative;
	/* 调整距离，避免与底部内容重叠 */
	background: #f1f1f1;
	padding: 20rpx;
	z-index: 999;
}

.legend-list {
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	gap: 16rpx;
}

.legend-item {
	display: flex;
	align-items: center;
	padding: 4rpx 10rpx;
}

.legend-icon {
	width: 40rpx;
	height: 40rpx;
	flex-shrink: 0;
}

.price-text,
.status-text {
	margin-left: 10rpx;
	font-size: 28rpx;
	color: #333;
	white-space: nowrap;
}

/* 添加情侣座样式 */
.couple-seat {
	border: 2rpx solid #FF69B4;
	border-radius: 10rpx;
}

/* 情侣座包裹容器 */
.couple-seat-wrapper {
	display: flex;
	border: 2rpx solid #FF69B4;
	margin-left: 0 !important;
	border-radius: 10rpx;
}

.couple-seat-wrapper .couple-seat {
	margin-left: 0 !important;
	border: none !important;
}

/* 情侣座图例样式 */
.couple-seat-demo {
	width: 82rpx;
	height: 40rpx;
	border: 2rpx solid #FF69B4;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 10rpx;
}

.couple-seat-demo image {
	width: 40rpx;
	height: 40rpx;
}

.seat-indicators {
	position: fixed;
	z-index: 100;
	transition: left 0.3s;
}

.seat-indicators view {
	font-size: 24rpx;
	text-align: center;
	color: #fff;
}

.movable-area {
	display: flex;
	justify-content: center;
	align-items: center;
	overflow: hidden;
	transform-origin: center center;
}

.movable-view {
	display: flex;
	flex-direction: column;
	align-items: center;
	transform-origin: center center;
	transition: transform 0.3s ease;
}

.seat-container {
	display: flex;
	justify-content: center;
	align-items: center;
	flex-wrap: wrap;
	padding: 20rpx;
}
</style>